package com.manager.cms.controller;

import com.manager.cms.bo.SysMenu;
import com.manager.cms.bo.UserRole;
import com.manager.cms.common.CommonResponse;
import com.manager.cms.service.SysMenuService;
import com.manager.cms.service.UserRoleService;
import com.manager.cms.vo.MenuTreeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 菜单栏
 *
 */
@Slf4j
@RestController
@RequestMapping("/sys/menu")
public class MenuController {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private UserRoleService userroleservice;

    @GetMapping("/menuList")
    public CommonResponse menuList(HttpServletRequest request) {
        String token = request.getHeader("token");
        UserRole userRole = new UserRole();
        userRole.setUserId(token);
        List<UserRole> list = userroleservice.getList(userRole);
        UserRole userRole1 = list.get(0);
        String role = userRole1.getRole();

        List<MenuTreeVO> menuTreeVOList = new ArrayList<>();
        List<SysMenu> sysMenusList = sysMenuService.selectAll();

        List<SysMenu> sysMenus = sysMenusList.stream().filter(t -> t.getAuthCode().contains(role)).collect(Collectors.toList());

        for (int i = 0; i < sysMenus.size(); i++) {
            SysMenu sysMenu = sysMenus.get(i);
            MenuTreeVO menuTreeVO = new MenuTreeVO();
            menuTreeVO.setId(sysMenu.getId() + "");
            menuTreeVO.setTitle(sysMenu.getMenuName());
            menuTreeVO.setIcon(sysMenu.getMenuIcon());
            menuTreeVO.setSpread(Boolean.FALSE);
            menuTreeVO.setHref(sysMenu.getMenuUrl());
            sysMenu.getChildren().forEach(o -> {
                MenuTreeVO menuTreeVOChild = new MenuTreeVO();
                menuTreeVOChild.setId(o.getId() + "");
                menuTreeVOChild.setTitle(o.getMenuName());
                menuTreeVOChild.setIcon(o.getMenuIcon());
                menuTreeVOChild.setSpread(Boolean.FALSE);
                menuTreeVOChild.setHref(o.getMenuUrl());
                menuTreeVO.getChildren().add(menuTreeVOChild);
            });
            menuTreeVOList.add(menuTreeVO);
        }

        return CommonResponse.succeed(menuTreeVOList);
    }

}
